package thread;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

//生产者消费者模型
public class ThreadDemo14 {
    //
    public static void test1() throws InterruptedException {
        BlockingQueue<String> queue = new LinkedBlockingQueue<>();
        //BlockingQueue<String> aqueue = new ArrayBlockingQueue<>(100);
        //入队
        queue.put("wsx");

        //阻塞队列中没有元素，直接 take() 就会阻塞
        String elem = queue.take();
        System.out.println(elem);
    }
    //生产者消费者
    public static void producerAndCustomer() throws InterruptedException {
        //阻塞队列
        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
        //消费线程
        Thread customer = new Thread(()->{
            while(true){
                try {
                    int elem = queue.take();
                    System.out.println("消费元素：" + elem);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者");
        //启动消费线程
        customer.start();

        //生产线程
        Thread producer = new Thread(()->{
            Random random = new Random(System.currentTimeMillis());
            while(true){
                try {
                    int elem = random.nextInt(1000);
                    System.out.println("生产元素：" + elem);
                    queue.put(elem);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "生产者");
        //启动生产线程
        producer.start();

        customer.join();
        producer.join();

    }
    public static void main(String[] args) throws InterruptedException {
        test1();
        producerAndCustomer();
    }
}

